package com.ldk.admin.factory;

import java.util.ArrayList;
import java.util.List;

import com.ldk.framework.entity.Menu;

public class MenuFactory {
	
	/**
	 * 菜单树建立器
	 * @param menus
	 * @return
	 */
	public List<MenuExt> build(List<Menu> menus)
	{
		if(menus == null) return null;
		List<MenuExt> menusExt = new ArrayList<MenuExt>();
		for(Menu menu: menus){
			//根菜单
			if(menu.getParentId() == 0){
				MenuExt menuExt = new MenuExt();
				menuExt.setMenuId(menu.getMenuId());
				menuExt.setMenuName(menu.getMenuName());
				menuExt.setParentId(menu.getParentId());
				menuExt.setActionUrl(menu.getActionUrl());
				menuExt.setEnabled(menu.getEnabled());
				menuExt.setMenuDesc(menu.getMenuDesc());
				menuExt.setIconCss(menu.getIconCss());
				menuExt.setIschecked(menu.getIschecked());
				
				List<MenuExt> children = buildChild(menu, menus);
				menuExt.setChildren(children);
				
				menusExt.add(menuExt);
			}
		}
		return menusExt;
	}
	
	private List<MenuExt> buildChild(Menu parent, List<Menu> menus){
		if(parent == null || menus == null) return null;
		List<MenuExt> menusExt = new ArrayList<MenuExt>();
		for(Menu menu:menus){
			//if(menu.getParentId() == parent.getMenuId()){
			if(menu.getParentId().intValue() == parent.getMenuId().intValue()){
				MenuExt menuExt = new MenuExt();
				menuExt.setMenuId(menu.getMenuId());
				menuExt.setMenuName(menu.getMenuName());
				menuExt.setParentId(menu.getParentId());
				menuExt.setActionUrl(menu.getActionUrl());
				menuExt.setEnabled(menu.getEnabled());
				menuExt.setMenuDesc(menu.getMenuDesc());
				menuExt.setIconCss(menu.getIconCss());
				menuExt.setIschecked(menu.getIschecked());
				
				List<MenuExt> children = buildChild(menu, menus);
				menuExt.setChildren(children);
				menusExt.add(menuExt);
				
				if(children == null) continue;
			}
		}
		return menusExt;
	}
}
